<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: version_upgrade.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * Installation template class
 *
 * @package Fusion Registry
 * @subpackage installer
 * @version $Id: version_upgrade.php 4 2008-08-03 01:43:03Z registry.fusion $
 */
if ( ! defined( 'IN_IPB' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
    exit();
}

class version_upgrade
{
    var $ipsclass;
    var $instagrade;
    var $this_version = '30000';
    var $upgrade_from = '20007';
    var $base_url     = '';
    var $mod_to_run   = '';


    /**
     * Generate the upgrades to happen string
     */
    function version_process()
    {
        $this->base_url  = "index.php?act=kit";

        if ( is_array( $this->instagrade->modules_to_run ) and count( $this->instagrade->modules_to_run ) )
        {
            $tmp = array_shift( $this->instagrade->modules_to_run );

            $this->mod_to_run = implode( ', ', $this->instagrade->modules_to_run );
        }

        if ( ! $this->mod_to_run )
        {
            $this->mod_to_run = 'None';
        }
    }


    /**
     * Oh how we love to upgrade!
     */
    function auto_run()
    {
        switch( $this->ipsclass->input['kitact'] )
        {
            case 'sql':
                $this->update_sql();
                break;

            case 'migrate_sql':
                $this->migrate_sql();
                break;

            default:
                $this->upgrade_kit_intro();
                break;
        }
    }


    /**
     * Create our new tables
     */
    function update_sql()
    {
        require './instagrade/sql_importer.php';

        $sql_importer = new sql_importer();
        $sql_importer->ipsclass =& $this->ipsclass;
        $sql_importer->auto_run();

        $executed = 0;

        // First install our new tables
        if ( file_exists( './upgrade_' . $this->instagrade->current_upgrade . '/mysql_updates.sql.php' ) )
        {
            $executed = $sql_importer->execute_sql_file('./upgrade_' . $this->instagrade->current_upgrade . '/mysql_updates.sql.php');
        }

        $this->instagrade->redirect( $this->base_url."&kitact=migrate_sql", "SQL updates complete, $executed queries run...." );
    }


    /**
     * Migrate the Garage Module tables to the new Fusion Registry schema
     *
     * Lots of logic and sql copy-paste. We are going to create a base of custom fields
     * that represent the default fields in the Garage Module.
     */
    function migrate_sql()
    {
        $executed = 0;

        // First things first, create the base custom fields
        //   year (s:4), color (s:128), mileage (i:10), mileage_units (s:32), price (i:10), currency (s:32), comments (t), make_id, model_id

        $field_txt = "(`field_name`, `field_type`, `field_options`, `field_default`, `field_required`, `field_size`, ".
                     "`field_rows`, `field_cols`, `field_order`, `field_browse`, `field_group_id`, `field_highlight`, `field_search`) ";

        $custom_fields = array(

            'year' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Year', 'S', 'year', '', 1, 4, 0, 0, 1, 1, 1, 1, 1)",

            'make_id' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Make', 'S', 'make', '', 1, 0, 0, 0, 2, 1, 1, 1, 1)",

            'model_id' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Model', 'S', 'model', '', 1, 0, 0, 0, 3, 1, 1, 1, 1)",

            'color' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Color', 'T', '', '', 0, 128, 0, 0, 4, 1, NULL, NULL, 0)",

            'mileage' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Mileage', 'T', '', '0', 0, 128, 0, 0, 5, 0, 2, NULL, 0)",

            'mileage_units' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Mileage Units', 'L', 'miles|Miles\nkm|Kilometers', 'miles', 0, 0, 0, 0, 6, 0, 2, NULL, 0)",

            'price' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Purchased Price', 'F', '', '', 0, 128, 0, 0, 7, 0, 3, NULL, 0)",

            'currency' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Currency', 'L', 'usd|USD\ncad|CAD\neur|EUR\npound|Pounds', 'usd', 0, 0, 0, 0, 8, 0, 3, NULL, 0)",

            'comments' =>
                "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_defs $field_txt ".
                "VALUES ('Description', 'M', '', '', 0, 0, 10, 60, 9, 0, NULL, NULL, 0)",
        );

        // Loop through and execute sql
        $field_ids = array();
        foreach ( $custom_fields as $field => $sql )
        {
            if ( !$this->ipsclass->DB->query($sql) )
            {
                $this->ipsclass->template->install_error($sql."<br /><br />".$this->ipsclass->DB->error);
            }

            // Keep track of id
            $field_ids[$field] = $this->ipsclass->DB->get_insert_id();

            $executed++;
        }


        // First we are going to do all the straight through copy/paste migrations because they are easy :)
        // These are straight "INSERT ... SELECT ... FROM ..." statements.

        // Images
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_images ".
                                          "( attach_id, attach_location, attach_hits, attach_ext, attach_file, ".
                                          "attach_thumb_location, attach_thumb_width, attach_thumb_height, ".
                                          "attach_is_image, attach_date, attach_filesize ) ".
                                    "SELECT i.attach_id, i.attach_location, i.attach_hits, i.attach_ext, i.attach_file, ".
                                          "i.attach_thumb_location, i.attach_thumb_width, i.attach_thumb_height, ".
                                          "i.attach_is_image, i.attach_date, i.attach_filesize ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_images AS i" );

        $executed++;

        // Gallery
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_gallery ".
                                          "( id, item_id, image_id ) ".
                                    "SELECT g.id, g.garage_id, g.image_id ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_gallery AS g" );

        $executed++;

        // Guestbooks
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_guestbooks ".
                                          "( id, item_id, author_id, post_date, ip_address, post ) ".
                                    "SELECT gb.id, gb.garage_id, gb.author_id, gb.post_date, gb.ip_address, gb.post ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_guestbooks AS gb" );

        $executed++;

        // Categories
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_categories ".
                                          "( id, title, image_id ) ".
                                    "SELECT c.id, c.title, c.image_id ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_categories AS c" );

        $executed++;

        // Makes
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_makes ".
                                          "( id, make ) ".
                                    "SELECT m.id, m.make ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_makes AS m" );

        $executed++;

        // Models
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_models ".
                                          "( id, make_id, model ) ".
                                    "SELECT m.id, m.make_id, m.model ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_models AS m" );

        $executed++;

        // Modifications
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_mods ".
                                          "( id, item_id, member_id, category_id, title, price, install_price, ".
                                          "rating, comments, image_id, date_created, date_updated ) ".
                                    "SELECT m.id, m.garage_id, m.member_id, m.category_id, m.title, m.price, ".
                                          "m.install_price, m.rating, m.comments, m.image_id, m.date_created, ".
                                          "m.date_updated ".
                                    "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_mods AS m" );

        $executed++;


        // Now we are going to tackle the hard migrations where data manipulation needs to occur.

        // Items
        $rs = $this->ipsclass->DB->query( "SELECT id, member_id, year, color, mileage, mileage_units, price, ".
                                              "currency, comments, image_id, views, date_created, date_updated, ".
                                              "make_id, model_id, guestbook_pm_notify ".
                                          "FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage" );

        while ( $existing = $this->ipsclass->DB->fetch_row($rs) )
        {
            // YE HA! Insert the base data, then go after the custom fields with a vengence!
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'id' => $existing['id'],
                                                                               'member_id' => $existing['member_id'],
                                                                               'image_id' => $existing['image_id'],
                                                                               'views' => $existing['views'],
                                                                               'date_created' => $existing['date_created'],
                                                                               'date_updated' => $existing['date_updated'],
                                                                               'guestbook_pm_notify' => $existing['guestbook_pm_notify'],
                                                                      )      );

            $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_items ".
                                        "( ".$db_string['FIELD_NAMES']." ) VALUES ( ".$db_string['FIELD_VALUES']." )" );

            $executed++;

            // Now loop through the custom fields
            foreach ( $field_ids as $field => $cf_id )
            {
                // Only add if we have data for this item
                if ( !empty( $existing[$field] ) )
                {
                    $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'field_id' => $cf_id,
                                                                                       'item_id' => $existing['id'],
                                                                                       'field_value' => $existing[$field],
                                                                              )      );

                    $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries ".
                                                "( ".$db_string['FIELD_NAMES']." ) VALUES ( ".$db_string['FIELD_VALUES']." )" );

                    $executed++;
                }
            }
        }


        // Configuration
        $this->ipsclass->DB->query( "SELECT * FROM ".$this->ipsclass->vars['sql_tbl_prefix']."garage_config" );

        $existing = $this->ipsclass->DB->fetch_row();

        // Holy config options Batman!
        $config_fields = array( 'max_user_cars', 'year_start', 'year_end', 'allow_bbcode_car', 'allow_bbcode_mod',
                                'allow_html_car', 'allow_html_mod', 'cars_per_page', 'allow_image_upload', 'max_image_kbytes',
                                'max_image_resolution', 'max_car_images', 'thumbnail_resolution', 'allow_mod_image',
                                'thumbnail_type', 'convert_path', 'convert_options', 'enable_guestbooks', 'enable_featured_vehicle',
                                'featured_vehicle_id', 'featured_vehicle_description', 'allow_image_url', 'browse_perms',
                                'add_perms', 'interact_perms', 'upload_perms', 'show_mod_gallery', 'limit_mod_gallery',
                                'limit_mod_gallery_amount', 'tmpl_newestvehicles_on', 'tmpl_newestvehicles_limit',
                                'tmpl_newestmods_on', 'tmpl_newestmods_limit', 'tmpl_mostmodded_on', 'tmpl_mostmodded_limit',
                                'tmpl_mostmoneyspent_on', 'tmpl_mostmoneyspent_limit', 'tmpl_mostviewed_on', 'tmpl_mostviewed_limit',
                                'tmpl_lastupdatedvehicles_on', 'tmpl_lastupdatedvehicles_limit', 'tmpl_lastupdatedvehiclesmain_on',
                                'tmpl_lastupdatedvehiclesmain_limit', 'tmpl_lastupdatedmods_on', 'tmpl_lastupdatedmods_limit',
                                'tmpl_lastcommented_on', 'tmpl_lastcommented_limit', 'date_format', 'remote_timeout',
                                'featured_vehicle_random' );

        foreach ( $config_fields as $old_name )
        {
            // vehicle => item
            $config_name = preg_replace("/vehicle/", 'item', $old_name);

            // entify convert_options/path
            if ( $old_name == 'convert_path' or $old_name == 'convert_options' )
            {
                $existing[$old_name] = htmlentities( $existing[$old_name] );
            }

            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'config_name' => $config_name,
                                                                               'config_value' => $existing[$old_name]
                                                                      )      );

            $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_config ".
                                        "( ".$db_string['FIELD_NAMES']." ) VALUES ( ".$db_string['FIELD_VALUES']." )" );

            $executed++;
        }

        $cleanup = array(
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='miles' WHERE field_value='Miles'",
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='km' WHERE field_value='Kilometers'",
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='usd' WHERE field_value='USD'",
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='cad' WHERE field_value='CAD'",
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='eur' WHERE field_value='EUR'",
            "UPDATE ".$this->ipsclass->vars['sql_tbl_prefix']."registry_field_entries set field_value='pounds' WHERE field_value='Pounds'"
        );

        // Some last minute cleanup :)
        foreach ( $cleanup as $sql )
        {
            $this->ipsclass->DB->query( $sql );
            $executed++;
        }

        // Add our version info to the db since this is the first version that introduced these
        $vers = array( 'version_long' => '30000',
                       'version_short' => 'v3.0.0' );

        foreach ( $vers as $name => $value )
        {
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'config_name' => $name,
                                                                               'config_value' => $value
                                                                      )      );

            $this->ipsclass->DB->query( "INSERT INTO ".$this->ipsclass->vars['sql_tbl_prefix']."registry_config ".
                                        "( ".$db_string['FIELD_NAMES']." ) VALUES ( ".$db_string['FIELD_VALUES']." )" );

            $executed++;
        }


        // All done
		$this->instagrade->redirect( "index.php?act=done", "Transition from Garage Module to Fusion Registry tables complete, $executed queries run...." );
    }


    /**
     * Print intro
     */
    function upgrade_kit_intro()
    {
        $this->ipsclass->template->print_header();

        $this->ipsclass->template->contents .= <<<HTML
This upgrade kit will upgrade you from <b>"{$this->instagrade->version_history[$this->upgrade_from]}"</b> to <b>"{$this->instagrade->version_history[$this->this_version]}"</b>
<br />
<br />
<div style='color:red;' align='center'><b>PLEASE NOTE:</b> Running this upgrade kit will drop any existing Fusion Registry tables!
<br />
<br /><b>DO NOT RUN THIS UPGRADE KIT IF YOU ALREADY HAVE FUSION REGISTRY INSTALLED AND RUNNING !!</b>
<br />
<br />This upgrade kit will not alter any Garage Module tables!</div>
<br />
<br />
<div align='center'><a href="{$this->base_url}&kitact=sql" class='button' style='color: #003366'>Continue >></a></div>
<br />
<br />
<div align='center'>Upgrade kits still to run after this upgrade: {$this->mod_to_run}</div>
HTML;

        $this->ipsclass->template->output();
    }

}


?>